package com.asdan.seededu.front.service.impl;

 import java.text.ParseException;

import org.springframework.stereotype.Service;

import com.asdan.seededu.entity.security.User;
import com.asdan.seededu.service.impl.UserServiceImpl;
import com.asdan.seededu.util.MD5Util;
import com.asdan.seededu.util.SendEmail;
import com.asdan.seededu.util.ServiceException;


 
/**
 * 
 * @author Qixuan.Chen
 */
@Service
public class RegisterValidateService {

   

    /**
     * 处理注册
     */

    public void processregister(String email){
        
        ///如果处于安全，可以将激活码处理的更复杂点，这里我稍做简单处理
        //user.setValidateCode(MD5Tool.MD5Encrypt(email));
        ///邮件的内容
        StringBuffer sb=new StringBuffer("点击下面链接激活账号，48小时生效，否则重新注册账号，链接只能使用一次，请尽快激活！</br>");
        sb.append("<a href=\"http://www.seededu.cn/user/action?email=");
        //sb.append("<a href=\"http://localhost:8090/seededu/user/action?email=");
        sb.append(email); 
        sb.append("&validateCode="); 
        sb.append(MD5Util.encode2hex(email));
        //sb.append("\">http://localhost:8090/seededu/user/action?email="); 
        sb.append("\">http://www.seededu.cn/user/action?email="); 
        sb.append(email);
        sb.append("&validateCode=");
        sb.append(MD5Util.encode2hex(email));
        sb.append("</a>");
        //发送邮件
        SendEmail.send(email, sb.toString());
        System.out.println("发送邮件");

    }

    /**
     * 处理激活
     * @throws ParseException 
     */
      ///传递激活码和email过来
    public void processActivate(String email , String validateCode)throws ServiceException, ParseException{  
         //数据访问层，通过email获取用户信息
        User user=new UserServiceImpl().getUser(email,0);
        //验证用户是否存在 
        if(user!=null) {  
            //验证用户激活状态  
        	System.out.println("user:"+user);
            if(user.getIsok()==0) { 
            	System.out.println("user.getIsok()");
                ///没激活
                //验证链接是否过期 
                    //验证激活码是否正确  
            		System.out.println(validateCode)  ;
                    if(validateCode.equals(user.getValidateCode())) {  
                        //激活成功， //并更新用户的激活状态，为已激活 
                    	System.out.println("validateCode.equals(user.getValidateCode())");
                        user.setIsok(1);//把状态改为激活
                        if(!new UserServiceImpl().updateUser(user)){
                        	 throw new ServiceException("验证失败,请重新验证!");  
                        }
                   }else {  
                       	throw new ServiceException("激活码不正确");  
                   }
           } 
        }else {
                    	throw new ServiceException("该邮箱未注册（邮箱地址不存在）！");  
        }  	

    }  
 }
 